package com.east.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;


public class UploadUtil {
	/**
	 * 构建目录
	 * 
	 * @param pathdir
	 *            目录的全路径
	 * @throws Exception
	 */
	public static void createDir(String pathdir) throws Exception {
		try {
			File dir = new File(pathdir);
			if (!dir.exists()) {
				dir.mkdirs();
			}
		} catch (Exception e) {
			System.err.println(new Date() + ":" + e.getLocalizedMessage());
		}
	}

	/**
	 * 上传文件*(一般上传)
	 * @param uploadfile  上传文件流
	 * @param targetpath 上传后的文件全路径名
	 * @throws Exception
	 */
	public static void upload(File uploadfile, String targetpath)
			throws Exception {
		try {
			FileInputStream fin = new FileInputStream(uploadfile);
			FileOutputStream fout = new FileOutputStream(targetpath);
			byte[] buf = new byte[20480];
			int bufsize = 0;
			while ((bufsize = fin.read(buf, 0, buf.length)) != -1) {
				fout.write(buf, 0, bufsize);
			}
			fin.close();
			fout.close();

		} catch (Exception e) {
			System.err.println(new Date() + ":" + e.getLocalizedMessage());
		}
	}

	/**
	 * 
	 * @param tempdir
	 * @param fileName
	 * @param in
	 * @return
	 * @throws Exception
	 */
	public static File upload(String tempdir, String fileName, InputStream in)
			throws Exception {
		File file = new File(tempdir + "/" + fileName);
		try {
			FileOutputStream fout = new FileOutputStream(file);
			byte[] buf = new byte[20480];
			int bufsize = 0;
			while ((bufsize = in.read(buf, 0, buf.length)) != -1) {
				fout.write(buf, 0, bufsize);
			}
			in.close();
			fout.close();

		} catch (Exception e) {
			System.err.println(new Date() + ":" + e.getLocalizedMessage());
		}
		return file;
	}

	/**
	 * 获得文件后缀
	 * 
	 * @param filename
	 * @return
	 */
	public static String getExt(String filename) {
		return filename.substring(filename.lastIndexOf('.') + 1).toLowerCase();
	}

	

	
}
